{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Summary: 理解TensorFlow程序结构\n",
    "Author:  Amusi\n",
    "Date:   2018-03-29\n",
    "Note:   这里是计算图和执行图的简单示例：对两个向量进行加法运算"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3 3 8 7]\n"
     ]
    }
   ],
   "source": [
    "# 定义图\n",
    "v_1 = tf.constant([1, 2, 3, 4])\n",
    "v_2 = tf.constant([2, 1, 5, 3])\n",
    "v_add = tf.add(v_1, v_2)  # 或者 v_add = v_1 + v_2\n",
    "\n",
    "# 使用tf.Session()执行图\n",
    "with tf.Session() as sess:\n",
    "    print(sess.run(v_add))\n",
    "    \n",
    "# 上述两行命令等价于下述代码.建议使用上述方式来执行图，因为使用with语句，就默认程序块结束后或自动close. 如果不要with，就要对Session进行close\n",
    "#sess = tf.Session()\n",
    "#print(sess.run(v_add))\n",
    "#sess.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "collapsed": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3 3 8 7]\n"
     ]
    }
   ],
   "source": [
    "# 使用tf.InteractiveSession()执行图，会直接定义为默认图，所以不需要调用session，比如下述中没有run方法\n",
    "sess = tf.InteractiveSession()\n",
    "\n",
    "v_1 = tf.constant([1, 2, 3, 4])\n",
    "v_2 = tf.constant([2, 1, 5, 3])\n",
    "v_add = tf.add(v_1, v_2)  # 或者 v_add = v_1 + v_2\n",
    "\n",
    "print(v_add.eval())\n",
    "sess.close()"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python [default]",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
